
import supplierApi from '../../model/supplier.js'
import {errorResult} from '../../utils/pubilc.js'


export default app => {

  /**
   * @description 查询供应商表
   * */
  app.get('/wpApi/getSupplierList', async (req, res) => {
    const {page, pageSize, name,} = req.query
    let result = {
      code: 0,
      msg: '数据异常',
      result: null
    }
    if(!page || !pageSize) {
      result = errorResult()
    }
    const skip = (page - 1 ) * pageSize
    let filter = {}
    if(name.trim()) {
      filter = {
        name: {
          $regex: name
        }
      }
    }
    const field = {_id: 0, __v: 0, _createTime: 0, _updateTime: 0}
    const count = await supplierApi.find(filter).count()
    const data = await supplierApi.find(filter, field ).skip(skip).limit(pageSize).sort({createTime: -1})
    result = {
      code: 0,
      msg: 'success',
      result: data,
      count
    }
    res.send(result)
  })

  /**
   * @description 新增供应商
   * */
  app.post('/wpApi/saveSupplier', async (req, res) => {

    const {company, name, phone, otherPhone, remarks} = req.body
    if(!company || !name || !phone ) {
      res.send(errorResult())
      return
    }
    supplierApi.create({
      company, name, phone, remarks, otherPhone
    }).then(() => {
      res.send({
        code: 0,
        msg: '操作成功'
      })
    }).catch((e) => {
      res.send({
        code: 1,
        msg: '系统错误：' + e
      })
    })

    
  })

  /**
   * @description 删除供应商
   * */
  app.post('/wpApi/deleteSupplier', async (req, res) => {

    const {id} = req.body
    if(!id) {
      res.send(errorResult())
      return
    }
    supplierApi.deleteOne({
      id
    }).then(() => {
      res.send({
        code: 0,
        msg: '操作成功'
      })
    }).catch((e) => {
      res.send({
        code: 1,
        msg: '系统错误：' + e
      })
    })
  })

}